<template>
  <view class="content">
    <image class="logo" src="/static/logo.png" />
    <view class="text-area">
      <text class="title">{{ title }}</text>
    </view>



    <!-- 根据 activeTab 显示不同内容 -->
    <view v-if="activeTab == 'login'" class="login-container">
      <uni-segmented-control :current="currentIndex" :values="items" styleType="text" @click-item="clickItem"
        class="segmented"></uni-segmented-control>
      <!-- 手机号输入框 -->
      <view class="input-item">
        <input type="number" placeholder="请输入手机号" v-model="phone" />
      </view>
      <!-- 验证码输入框 -->
      <view class="input-item" v-if="currentIndex == 1">
        <input type="number" placeholder="请输入验证码" v-model="verificationCode" />
        <button :disabled="isSendingCode" @click="sendVerificationCode">
          {{ isSendingCode ? registerCountdown + ' s后重试' : '发送验证码' }}
        </button>
      </view>
      <view v-if="currentIndex === 0" class="input-item">
        <input v-model="password" placeholder="请输入密码" placeholder-class="input-placeholder" @input="" />
      </view>
      <view class="tips" :class="{ animate__shakeY: isAgreePrivacyShakeY }">
        <label class="label" @tap="isAgreePrivacy = !isAgreePrivacy">
          <radio class="radio" color="#28bb9c" :checked="isAgreePrivacy" />
          <text>登录/注册即视为你同意</text>
        </label>
        <navigator class="link" hover-class="none" url="./protocal">《服务条款》</navigator>
        和
        <text class="link" @tap="onOpenPrivacyContract">《隐私协议》</text>
      </view>
      <!-- 登录按钮 -->
      <button class="login-btn" @click="login">登录</button>
      <text class="goToRegister" @tap="goToRegister">还没有账号？去注册</text>
    </view>
    <view v-if="activeTab == 'register'" class="register-container">
      <!-- 用户注册输入框 -->
      <view class="input-item">
        <input type="number" placeholder="请输入手机号" v-model="registerPhone" />
      </view>
      <view class="input-item">
        <input type="number" placeholder="获取验证码" v-model="registerVerificationCode" />
        <button :disabled="isRegisterSendingCode" @click="sendRegisterVerificationCode">
          {{ isRegisterSendingCode ? registerCountdown + ' s后重试' : '发送验证码' }}
        </button>
      </view>
      <view class="input-item">
        <input type="password" placeholder="设置密码" v-model="registerPassword" />
      </view>
      <view class="input-item">
        <input type="password" placeholder="确认密码" v-model="confirmPassword" />
      </view>
      <!-- 注册按钮 -->
      <button class="login-btn" @click="register">注册</button>
      <text class="goToRegister" @tap="goToLogin">已经有账号了，去登录</text>

      <!-- 添加与登录页面相同的提示 -->
      <view class="tips" :class="{ animate__shakeY: isAgreePrivacyShakeY }">
        <label class="label" @tap="isAgreePrivacy = !isAgreePrivacy">
          <radio class="radio" color="#28bb9c" :checked="isAgreePrivacy" />
          <text>登录/注册即视为你同意</text>
        </label>
        <navigator class="link" hover-class="none" url="./protocal">《服务条款》</navigator>
        和
        <text class="link" @tap="onOpenPrivacyContract">《隐私协议》</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { getVerificationCode, loginAPI, loginAPIByPassword, registerAPI} from '@/service/login'
import type { loginType, loginTypeByPassword,registerType} from '@/types/login'
import { onLoad } from '@dcloudio/uni-app'

import { useMemberStore } from '@/stores'

const memberStore = useMemberStore()

const title = ref('Hello')
const activeTab = ref<string>('login') // 控制”“登录“和”注册“的两个状态
const currentIndex = ref(0) //控制”密码登录 1“和”验证码登录 0“的两个状态
const items = ref(['密码登录', '验证码登录']) // 分段器选项
const password = ref('');

// 验证码登录相关数据
const phone = ref('')
const verificationCode = ref('')
const isSendingCode = ref(false)
const countdown = ref(60)
const isAgreePrivacy = ref(false)
const isAgreePrivacyShakeY = ref(false)

// 用户注册相关数据
const registerPhone = ref('') //请求
const registerVerificationCode = ref('') //请求
const registerPassword = ref('') //请求

const confirmPassword = ref('')
const isRegisterSendingCode = ref(false)
const registerCountdown = ref(60)



// 发送验证码
const sendVerificationCode = async () => {
  isSendingCode.value = true
  isRegisterSendingCode.value = true
  console.log("倒计时开始")
  // 页面加载时执行的操作
  setInterval(() => {
    registerCountdown.value--;
    if (registerCountdown.value <= 0) {
      isRegisterSendingCode.value = false;
      isSendingCode.value = false;
      registerCountdown.value = 60;
    }
  }, 1000)
  console.log("发送登录验证码")
  if (!isAgreePrivacy.value) {
    uni.showToast({
      icon: 'none',
      title: '请先阅读并勾选协议',
    })
    isSendingCode.value = true
    setTimeout(() => {
      isSendingCode.value = true;
    }, 500)
    return
  }

  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phoneRegex.test(phone.value)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    })
    return
  }
  isSendingCode.value = true
  const timer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--
    } else {
      clearInterval(timer)
      isSendingCode.value = false
      countdown.value = 60
    }
  }, 1000)

  try {
    const res = await getVerificationCode(phone.value)
    console.log(res.data)
  } catch (error) {
    console.error('获取验证码失败:', error)
  }
}

// 点击分段器选项（密码登录或者验证码登录）
const clickItem = (e) =>{
  if (currentIndex.value !== e.currentIndex) {
    currentIndex.value = e.currentIndex
    
    console.log(currentIndex.value + " currentIndex的值")
  }
}
 
//点击去注册
const goToRegister = () => {
  activeTab.value = 'register'
  console.log(activeTab.value + " activeTab的值")
  currentIndex.value = 0
}

//点击去登录
const goToLogin = () => {
  activeTab.value ='login'
  console.log(activeTab.value + " activeTab的值")
  currentIndex.value = 0 
}

// 登录请求
const login = async () => {
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phoneRegex.test(phone.value)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    })
    return
  }
  if (verificationCode.value.length === 0 && activeTab.value === 'login' && currentIndex.value === 1) {
    uni.showToast({
      title: '请输入验证码',
      icon: 'none'
    })

    if (password.value.length === 0 && activeTab.value === 'login' && currentIndex.value === 0) {
      uni.showToast({
        title: '请输入密码',
        icon: 'none'
      })
    }
    uni.showToast({
      title: '请输入验证码',
      icon: 'none'
    })
    return
  }

  const loginData: loginType = {
    phone: phone.value,
    verificationCode: verificationCode.value
  }
  const loginData2:loginTypeByPassword = {
    phone: phone.value,
    password: password.value
  }
  if(currentIndex.value === 1){
    try {
      const res = await loginAPI(loginData)
      const token = res.data
      memberStore.setProfile({
        token: token,
        id: 100,
        nickname: '张三' ,
        introduction: '这是一个简介',
        avatarUrl: 'URL_ADDRESS',
        phone: '12345678901',
      })
      console.log(res.data)//token
    } catch (error) {
      console.error('登录失败:', error)
    } 
  }else if(currentIndex.value === 0){
    try {
      const res = await loginAPIByPassword(loginData2)
      const token = res.data
      memberStore.setProfile({
        token: token,
        id: 100,
        nickname: '张三',
        introduction: '这是一个简介',
        avatarUrl: 'URL_ADDRESS',
        phone: '12345678901',
      })
      console.log(res.data)
    } catch (error) {
      console.error('登录失败:', error)
    } 
  }
}


// 发送注册验证码
const sendRegisterVerificationCode = async () => {
  isSendingCode.value = true
  isRegisterSendingCode.value = true
  console.log("倒计时开始")
  // 页面加载时执行的操作
  setInterval(() => {
    registerCountdown.value--;
    if (registerCountdown.value <= 0) {
      isRegisterSendingCode.value = false;
      isSendingCode.value = false;
      registerCountdown.value = 60;
    }
  }, 1000) 
  console.log("发送注册验证码")
  if (!isAgreePrivacy.value) {
    uni.showToast({
      icon: 'none',
      title: '请先阅读并勾选协议',
    })
    isRegisterSendingCode.value = true
    setTimeout(() => {
      isRegisterSendingCode.value = false
    }, 500)
    return
  }
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phoneRegex.test(registerPhone.value)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    })
    return
  }
  isRegisterSendingCode.value = true
  const timer = setInterval(() => {
    if (registerCountdown.value > 0) {
      registerCountdown.value--
    } else {
      clearInterval(timer)
      isRegisterSendingCode.value = false
      registerCountdown.value = 60
    }
  }, 1000)

  try {
    const res = await getVerificationCode(registerPhone.value)
    console.log(res.data)
  } catch (error) {
    console.error('获取注册验证码失败:', error)
  }
}

const timeDec = () => {
  isSendingCode.value = true
  isRegisterSendingCode.value = true
  console.log("倒计时开始")
  // 页面加载时执行的操作
  setInterval(() => {
    registerCountdown.value--;
    if (registerCountdown.value <= 0) {
      isRegisterSendingCode.value = false;
      isSendingCode.value = false;
      registerCountdown.value = 60;
    }
  }, 1000) 
}

// 注册请求
const register = async () => {
  if (!isAgreePrivacy.value) {
    uni.showToast({
      icon: 'none',
      title: '请先阅读并勾选协议',
    })
    isAgreePrivacyShakeY.value = true
    setTimeout(() => {
      isAgreePrivacyShakeY.value = false
    }, 500)
    return
  }
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phoneRegex.test(registerPhone.value)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    })
    return
  }
  if (registerVerificationCode.value.length === 0) {
    uni.showToast({
      title: '请输入验证码',
      icon: 'none'
    })
    return
  }
  if (registerPassword.value.length === 0) {
    uni.showToast({
      title: '请设置密码',
      icon: 'none'
    })
    return
  }
  if (registerPassword.value !== confirmPassword.value) {
    uni.showToast({
      title: '两次输入的密码不一致',
      icon: 'none'
    })
    return
  }

  const registerData = ref<registerType>({
    phone: registerPhone.value,
    verificationCode: registerVerificationCode.value,
    password: registerPassword.value,
  })
  // 这里需要添加注册接口调用
  try {
    const res = await registerAPI(registerData.value)
    console.log('注册成功')
  } catch (error) {
    console.error('注册失败:', error)
  }
}

// 打开隐私协议
const onOpenPrivacyContract = () => {
  // 实现打开隐私协议逻辑
}
</script>

<style scoped>
.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.logo {
  height: 200rpx;
  width: 200rpx;
  margin-top: 200rpx;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 50rpx;
}

.text-area {
  display: flex;
  justify-content: center;
  width: 100%;
  height: 80rpx;
  font-size: 28rpx;
  border: none; 
  padding-left: 30rpx;
  margin-bottom: 20rpx;
      
}

.title {
  font-size: 36rpx;
  color: #8f8f94;
  
}

.segmented {
  width:1000rpx;
  height: 80rpx;
  margin-bottom: 30rpx; 
 
  
}

.login-container,
.register-container {
  
  margin-top: 50rpx;
  width: 80%;
  margin-bottom: 100rpx;
  left: 60%;
  margin-left: -20px;
}
 /* 登录输入框样式 */
.input-item {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20rpx;
  margin-top:20rpx;
  border: 1rpx solid #ccc; 
  border-radius: 8rpx; 
  padding: 20rpx;
  width: 100%;
  height: 60rpx;
}

.input-item input {
  flex: 1;
}
 /* 验证码输入框样式 */
.input-item button {
  margin-left: 20rpx;
  font-size: 24rpx;
  white-space: nowrap;
  background-color: transparent;
  width: 30%;
  height: 50rpx;
  line-height: 50rpx;
  color: #8f8f94;
  border: none;
  padding: 0;
}

.login-btn {
  width: 108%;
  background-color: #2196F3;
  color: white;
  border: none;
  border-radius: 8rpx;
  padding: 20rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.tips {
  position: fixed;
  bottom: 30rpx;
  left: 0;
  right: 0;
  text-align: center;
  color:#8f8f94;
  font-size: 24rpx;
  white-space: nowrap;
}

.tips .label,
.tips .link {
  display: inline;
  vertical-align: middle;
}

.tips .radio {
  vertical-align: middle;
  margin-right: 10rpx;
}

.goToRegister{
  display: flex;
  color: #2196F3;
  font-size: 26rpx;
  margin-top: 30rpx;
  margin-left: 56%;
}
</style>
